var express = require('express');
var router = express.Router();
var Role = require('../model/role');
//添加新的角色
router.post('/entry', (req, res, next) => {
  var roleObj = req.body.roleObj;
  //根据数据库中的长度生产id
  Role.find({}, (err, docs) => {
    var roleId;
    if (docs.length!==0) {
       roleId = parseInt(docs[docs.length - 1].roleId) + 1;
    }else {
       roleId=1000;
    }
    //document对应model的实例，所以新建一个实例就是新建一个document
    var roleDoc = new Role({
      'roleId': roleId,
      'roleName': roleObj.roleName,
      'roleDescription': roleObj.roleDescription,
      'functionList': roleObj.functionList
    });
    //同步到数据库
    roleDoc.save((err, docs) => {
      if (err) {
        res.json({
          status: '0',
          msg: 'err',
          result: ''
        })
      } else {
        res.json({
          status: '1',
          msg: 'suc',
          result: ''
        })
      }
    });
  });
});
//选出所有的角色
router.get('/getAll', (req, res, next) => {
  Role.find({}, (err, doc) => {
    if (err) {
      res.json({
        status: '0',
        msg: 'err',
        result: ''
      })
    } else {
      res.json({
        status: '1',
        msg: 'suc',
        result: doc
      })
    }
  })
});
//删除角色
router.post('/delRole', (req, res, next) => {
  var roleId = req.body.roleId;
  Role.remove({roleId}, (err, doc) => {
    if (err) {
      res.json({
        status: '0',
        msg: err.message(),
        result: ''
      })
    } else {
      res.json({
        status: '1',
        msg: 'suc',
        result: ''
      })
    }
  })
});
//修改角色
router.post('/modifyRole', (req, res, next) => {
  var roleObj = req.body.roleObj;
  Role.update(
    {roleId: roleObj.roleId},
    {$set: {roleName: roleObj.roleName, roleDescription: roleObj.roleDescription, functionList: roleObj.functionList}},
    (err, doc) => {
      if (err) {
        res.json({
          status: '0',
          msg: err.message(),
          result: ''
        })
      } else {
        res.json({
          status: '1',
          msg: 'suc',
          result: doc
        })
      }
    }
  )
});
//根据名字查找
router.post('/getRoleByName', (req, res, next) => {
  var roleName = req.body.roleName;
  Role.findOne({roleName},(err,doc)=>{
    if (err){
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    } else {
      if (doc){
        res.json({
          status: '1',
          msg: 'suc',
          result: doc.functionList
        })
      } else {
        res.json({
          status: '1',
          msg: 'role is not found',
          result: ''
        })
      }
    }
  })
})
module.exports = router;
